import { Injectable } from '@nestjs/common';
import { writeFileSync } from 'fs';
import { EventsGateway } from '../events/events.gateway';
import { Files } from './file';
import { ip } from '../../config';
import { isLocal } from '../../env';

@Injectable()
export class FileService {
  constructor(private readonly eventsGateway: EventsGateway) {}
  saveFile(files: Files) {
    const res = {} as { [key in keyof Files]: string };
    let key: keyof Files;
    for (key in files) {
      const file = files[key][0];
      const getPath = () => {
        if (key === 'file') return '/data/' + file.originalname;

        const name = file.originalname;
        const index = name.lastIndexOf('.');
        const a = name.slice(0, index);
        const b = name.slice(index, name.length);
        return '/data/' + a + '-compress' + b;
      };
      const path = getPath();
      writeFileSync(path, file.buffer);
      const ipTmp = isLocal ? 'localhost' : ip;
      res[key] = `http://${ipTmp}${path}`;
    }
    if (res.compressedFile) return res.compressedFile;
    return res.file;
  }
}
